/**
 * Created by Administrator on 2017/4/20.
 */


var Poker = require('../Poker/Poker');
var NN = require('../Poker/NN');

var PokerPlayer = require('../Poker/player').PokerPlayer;

var Const = require('./const');
var SubCode = require('../subCode');
var Rule = require('./rules');

exports.WNNNPlayer = PokerPlayer.extend({
    _robDealer: -1,             // 抢庄状态，-1/0/1 未选择/不抢/抢庄
    _selectedCards: null,     // 选择的三张牌

    init: function (uid, msg) {
        this._super(uid, msg);


        this._baseScore = 0;
        this._selectedCards = null;

        this.winNums = 0;
        this.defeated = 0;
        this.hasNiu = 0;
        this.noneNiu = 0;

        this._stat.roundPattern = -1;
        this.isSelected = false;
    },

    setRotDealer: function (value) {
        this._robDealer = value;
    },

    getRobDealer: function () {
        return this._robDealer;
    },
    setBaseScore: function (score) {
        this._baseScore = score;
    },
    getBaseScore: function () {
        return this._baseScore;
    },

    setSelectedCards: function (cardsArr) {
        if (!cardsArr || cardsArr.length == 0) {
            this._selectedCards = [];
            return true;
        }

        if (cardsArr.length != 3) {
            return false;
        }

        var cards = Poker.buildFromArray(cardsArr);
        var allExist = true;
        var allPoint = 0;

        ExObject.eachKeyNum(cards, function (card, num) {
            if (!card) {
                allExist = false;
            }

            if (this._handCards.getCardNum(card) < num) {
                allExist = false;
            }

            allPoint += NN.getPoint(card) * num;
        }.bind(this));

        if (!allExist) {
            return false;
        }

        if (allPoint % NN.BASE != 0) {
            return false;
        }

        this._selectedCards = [];
        cardsArr.forEach(function (card) {
            this._selectedCards.push(card);
        }.bind(this));

        return true;
    },

    isSelectedCards: function () {
        return (this._selectedCards) ? true : false;
    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getInfo: function () {
        var info = this._super();
        info.remainScore = this._stat.remainScore;
        return info;
    },

    getReconnectInfo: function (isSelf) {
        var info = this._super(isSelf);

        //info.robDealer = this._robDealer;

        if (isSelf) {
            info.selectCards = this._selectedCards;
            info.handCards = this._handCards.getInitCards();

        }
        info.isSelected = this.isSelected;
        info.score = this.getScore();
        info.roundScore = this.getRoundScore()
        info.baseScore = this.getBaseScore();
        info.pattern = this._stat.roundPattern;
        info.selectNum = (this._selectedCards) ? this._selectedCards.length : -1;

        return info;
    },

    getSettlementInfo: function () {
        var info = this._super();

        info.handCards = this._handCards.getInitCards();
        info.selectCards = this._selectedCards;
        var room = this.getRoom();
        if (room.selected) {
            if (this.getRoundScore() > 0) {
                this.winNums += 1;
            } else {
                this.defeated += 1;
            }
            if (this._stat.roundPattern > 1) {
                this.hasNiu += 1;
            } else {
                this.noneNiu += 1;
            }
        }
        info.winNums = this.winNums;
        info.defeated = this.defeated;
        info.hasNiu = this.hasNiu;
        info.noneNiu = this.noneNiu;
        info.baseScore = this.baseScore;
        return info;
    },

    settlementPattern: function () {
        if (!this._selectedCards) {
            //自动选出最优三张牌
            var results = NN.calcNiuCards(this._handCards.getInitCards());
            this._selectedCards = (results.length > 0) ? results[0] : [];
        }

        this._calcNiu();
    },

    settlement: function () {
        this._super();

        var room = this.getRoom();
        var player = this;

        if (room.MSMode == "LLZZ" || room.MSMode == "SJZZ" || room.MSMode == "BZ") {
            console.log("settttlement")
            var ePlayer = this.getRoom().getDealerPlayer();
            if (!ePlayer) {
                return;
            }
            if (!room.selected) {
                return;
            }

            if (this.uid() == ePlayer.uid()) {
                return;
            }
            var RobFB = 1;
            // if (room.MS == "KPQZ" && ePlayer.getRobDealer() > 0) {
            //     RobFB = ePlayer.getRobDealer();
            // }

            if (ePlayer._stat.roundPattern > player._stat.roundPattern) {
                var score = player.getBaseScore() * Const.PatternMulti[ePlayer._stat.roundPattern];
                score *= RobFB;
                //var score = Const.PatternScore[ePlayer._stat.roundPattern];
                ePlayer.addRoundScore(score);
                player.addRoundScore(-score);
                console.log(score)

            } else if (ePlayer._stat.roundPattern < player._stat.roundPattern) {
                var score = player.getBaseScore() * Const.PatternMulti[player._stat.roundPattern];
                //var score = Const.PatternScore[player._stat.roundPattern];

                score *= RobFB;
                player.addRoundScore(score);

                ePlayer.addRoundScore(-score);

                console.log(score)

            } else {
                //var score = Const.PatternScore[player._stat.roundPattern];

                var ePlayCard = ePlayer._getMaxCard();
                var playerCard = player._getMaxCard();
                if (ePlayer._stat.roundPattern == Const.Pattern.NONE) {
                    console.log(playerCard);
                    if (Poker.getPoint(playerCard) <= 8) {
                        var score = player.getBaseScore() * Const.PatternMulti[ePlayer._stat.roundPattern];
                        score *= RobFB;
                        ePlayer.addRoundScore(score);
                        player.addRoundScore(-score);
                        return;
                    }
                }
                if (NN.cardLT(ePlayCard, playerCard)) {
                    var score = player.getBaseScore() * Const.PatternMulti[ePlayer._stat.roundPattern];
                    score *= RobFB;
                    ePlayer.addRoundScore(score);
                    player.addRoundScore(-score);

                } else {
                    var score = player.getBaseScore() * Const.PatternMulti[ePlayer._stat.roundPattern];
                    score *= RobFB;
                    player.addRoundScore(score);
                    ePlayer.addRoundScore(-score);
                    console.log(score)

                }

            }
        }
    },

    onStartNewRound: function () {
        this._super();

        this._selectedCards = null;
        this._baseScore = 0;
        this._stat.roundPattern = -1;
        this.isSelected = false;
    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    /******************************************************************
     * 私有功能函数
     ******************************************************************/
    _specialRule: function (pattern) {
        //var pattern = Const.Pattern.NONE;
        var room = this.getRoom();
        console.log("special Rulle");
        if (room.playStyle) {
            var allCardsArr = this._handCards.getInitCards();
            if (Rule.isSliverBull(allCardsArr.slice())) {
                pattern = Const.Pattern.YIN;
            }
            if (Rule.isGoldBull(allCardsArr.slice())) {
                pattern = Const.Pattern.JIN;
            }
            if (Rule.isFiveCalf(allCardsArr.slice())) {
                pattern = Const.Pattern.WXN;
            }
            if (Rule.isBomb(allCardsArr.slice())) {
                pattern = Const.Pattern.ZDN;
            }
            console.log(Rule.isDragon(allCardsArr.slice()))
            if (Rule.isDragon(allCardsArr.slice())) {
                pattern = Const.Pattern.YTL;
            }
        }
        return pattern;
    },
    _calcNiu: function () {
        var selectCards = this._selectedCards;
        if (!selectCards || selectCards.length == 0) {
            var pattern = Const.Pattern.NONE;
            this._stat.roundPattern = this._specialRule(pattern);
            return;
        }


        var allCardsArr = this._handCards.getInitCards();
        var otherPoints = 0;
        allCardsArr.forEach(function (card) {
            if (selectCards.indexOf(card) == -1) {
                otherPoints += NN.getPoint(card);
            }
        });

        var nPoint = otherPoints % NN.BASE;
        var pattern = Const.Pattern.NONE;

        if (nPoint == 0) {
            pattern = Const.Pattern.NN;
        } else {
            pattern = Const.Pattern['N' + nPoint];
        }

        //特殊规则
        this._stat.roundPattern = this._specialRule(pattern);
    },
    _cardArrayToObj: function (arrayCards) {
        var obj = {};
        arrayCards.forEach(function (v) {
            if (obj[v]) {
                obj[v] += 1;
            } else {
                obj[v] = 1;
            }
        });
        return obj;
    },
    _cardObjToArray: function (arrayObj) {
        var keys = Object.keys(arrayObj);
        var temp = [];
        keys.forEach(function (v) {
            if (arrayObj[v]) {
                temp.push(v);
            }
        });
        return temp;
    },

    _getMaxCard: function () {
        if (this._stat.roundPattern == Const.Pattern.ZDN) {

            var allCardsArr = this._handCards.getInitCards();
            var temp = allCardsArr.slice();
            temp.sort(function (a, b) {
                return Poker.getPoint(a) > Poker.getPoint(b);
            });

            if (Poker.getPoint(temp[0]) == Poker.getPoint(temp[1])) {
                return temp[0];
            } else {
                return temp[1];
            }
        }
        var maxCard = 0;
        //var selectCards = this._selectedCards;
        var allCardsArr = this._handCards.getInitCards();

        allCardsArr.forEach(function (card) {

            if (!maxCard || NN.cardLT(card, maxCard)) {
                maxCard = card;
            }

        });

        return maxCard;
    },
    // getInitHandCardPreCards: function () {

    //     var preCards = [];
    //     if (this._prehandcards) {
    //         for (var i = 0; i < this._prehandcards.length; i++) {
    //             preCards.push(this._prehandcards[i]);
    //         }
    //     }
    //     var distance = this.getRoom().getIndexDistance(this.getIndex(), this.getRoom().getDealerIndex());
    //     console.log("distanceee")
    //     console.log(distance);
    //     if (distance == 0) {
    //         preCards.push(202);
    //         preCards.push(102);
    //         preCards.push(104);
    //         preCards.push(107);
    //         preCards.push(108);



    //     } else if (distance == 1 || distance == 4 || distance == 2) {
    //         preCards.push(302);
    //         preCards.push(402);
    //         preCards.push(204);
    //         preCards.push(207);
    //         preCards.push(208);


    //     }
    //     //else if (distance == 2 || distance == 5) {
    //     // preCards.push(201);
    //     // preCards.push(202);
    //     // preCards.push(203);
    //     // preCards.push(204);
    //     // preCards.push(205);
    //     // 102,202,302,402,209
    //     //}
    //     var room = this.getRoom();
    //     logger.debug("room=%d noPreCards %j,cards = %j", room.rid(), preCards, this._prehandcards);

    //     return preCards;
    // },
});